package com.example.studentregistration.controller;

import com.example.studentregistration.pojo.CheckIn;
import com.example.studentregistration.service.CheckInService;
import com.example.studentregistration.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import java.io.InputStream;

@RestController
@RequestMapping("/api")
public class CheckInController {

    @Autowired
    private CheckInService checkInService;

    // 办理入住
    @PostMapping("/checkIn/add")
    public Result<?> add(@RequestBody CheckIn entity) {
        return checkInService.checkIn(entity);
    }

    // 修改入住记录（非业务状态变更）
    @PutMapping("/checkIn/update")
    public Result<?> update(@RequestBody CheckIn entity) {
        return checkInService.update(entity);
    }

    // 删除入住记录
    @DeleteMapping("/checkIn/delete/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        return checkInService.delete(id);
    }

    // 批量删除
    @PostMapping("/checkIn/batchDelete")
    public Result<?> batchDelete(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.fail("请选择要删除的记录");
        }
        int result = checkInService.batchDelete(ids);
        if (result > 0) {
            return Result.success("删除成功" + result + "条记录");
        }
        return Result.fail("删除失败");
    }

    // 退宿（根据记录ID）
    @PutMapping("/checkIn/checkout/{id}")
    public Result<?> checkout(@PathVariable Integer id) {
        return checkInService.checkOut(id);
    }

    // 调换（根据记录ID调换到目标房间与床位）
    @PutMapping("/checkIn/transfer")
    public Result<?> transfer(@RequestParam Integer recordId,
                              @RequestParam Integer targetRoomId,
                              @RequestParam String targetBedNo) {
        return checkInService.transfer(recordId, targetRoomId, targetBedNo);
    }

    // 分页查询
    @GetMapping("/checkIn")
    public Result<PageInfo<Object>> queryAll(@RequestParam(defaultValue = "1") Integer currentPage,
                                             @RequestParam(defaultValue = "10") Integer pageSize) {
        Page page = checkInService.queryAll(currentPage, pageSize);
        return Result.success(new PageInfo<>(page));
    }

    // 根据ID查询
    @GetMapping("/checkIn/queryById/{id}")
    public Result<CheckIn> queryById(@PathVariable Integer id) {
        return checkInService.queryById(id);
    }

    // 导出入住记录
    @GetMapping("/checkIn/export")
    public void export(HttpServletResponse response) throws IOException {
        checkInService.exportExcel(response);
    }

    // 导入入住记录
    @PostMapping("/checkIn/import")
    public Result<?> importCheckInExcel(@RequestPart("file") MultipartFile file) throws IOException {
        InputStream is = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(is);
        List<CheckIn> list = reader.readAll(CheckIn.class);
        int success = 0;
        for (CheckIn item : list) {
            try {
                // 使用业务办理流程，保证统计与校验一致
                if (checkInService.checkIn(item).getCode() == 200) {
                    success++;
                }
            } catch (Exception ignored) {}
        }
        if (success == list.size()) {
            return Result.success("导入成功");
        } else if (success > 0) {
            return Result.success("部分导入成功：" + success + "/" + list.size());
        } else {
            return Result.fail("导入失败");
        }
    }
}